<template>
    <el-form :model="form" ref="formRef" label-width="80px" v-loading="formLoading">
        <el-form-item label="组名" prop="name">
            <el-input v-model="form.name" clearable />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
            <el-input-number :min="0" v-model="form.sort" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
            <el-input v-model="form.description" clearable />
        </el-form-item>
        <el-form-item label="组图标" prop="icon">
            <el-input v-model="form.icon" clearable />
        </el-form-item>
        <el-form-item label="所属分类" prop="categoryName">
            <el-cascader style="width: 300px;" v-model="categoryArray" :options="options" :props="cascaderProps" />
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submit" :loading="loading">确定</el-button>
        </el-form-item>
    </el-form>
</template>

<script setup lang="ts" name="AddOrEditPmsAttrGroup">
import { ref, reactive, onMounted } from 'vue';
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus';
import type { pmsAttrGroupType } from '@/api/mall/pmsAttrGroup/types';
import type { pmsCategoryType } from '@/api/mall/pmsCategory/types';
import { pmsCategoryListTree } from '@/api/mall/pmsCategory';
import { commonCreateOrEdit, commonGetById } from '@/api/common/CommonAPI';
import { API } from '@/api/mall/pmsAttrGroup';

const props = defineProps(['isEdit', 'id'])
const emit = defineEmits(['success'])

const loading = ref(false)
const formLoading = ref(false)
let form = reactive<pmsAttrGroupType>({ sort: 0 })
const formRef = ref<FormInstance>()

onMounted(() => {
    loadPmsAttrGroup()
})

const loadPmsAttrGroup = async () => {
    try {
        formLoading.value = true
        if (props.isEdit) {
            const data = await commonGetById<pmsAttrGroupType>(API.GET_BY_ID, props.id)
            Object.assign(form, data.data)
            categoryArray.value = data.data.categoryArray
        }
        await categoryList();
    } finally {
        formLoading.value = false
    }
}

const submit = async () => {
    await formRef.value?.validate()
    try {
        loading.value = true
        form.categoryId = categoryArray.value?.at(-1)
        const data = await commonCreateOrEdit(API.CREATE_OR_EDIT, form)
        if (data.code === 200) {
            ElMessage.success(props.isEdit ? '修改成功' : '添加成功')
            emit('success')
        }
    } finally {
        loading.value = false
    }
}

//------所属分类
const options = ref<pmsCategoryType[]>()
const categoryArray = ref()
const cascaderProps = {
    children: 'children',
    label: 'name',
    value: 'catId'
}
// 所有的分类
const categoryList = async () => {
    const data = await pmsCategoryListTree()
    options.value = data.data
}
</script>

<style scoped lang="scss"></style>